package com.app.couponsharelife.ui.view
import android.app.Notification
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import cn.jpush.android.api.JPushInterface
import org.json.JSONException
import org.json.JSONObject
import android.app.NotificationManager
import android.app.NotificationChannel
import android.content.Context.NOTIFICATION_SERVICE
import android.app.PendingIntent
import android.os.Build
import androidx.core.app.NotificationCompat
import com.app.couponsharelife.R
import com.app.couponsharelife.ui.main.MainActivity
import com.app.couponsharelife.ui.main.SplashActivity
import com.app.couponsharelife.utils.AppUtils
import me.leolin.shortcutbadger.ShortcutBadger

/**
 *Created by xct on 2019/5/30
 *Description:
 */
class MyReceiver:BroadcastReceiver() {
    private val TAG = "JIGUANG-Example"
    private var messageNumber=0
    override fun onReceive(context: Context, intent: Intent) {
        try {
            val bundle = intent.extras
            //Log.d(TAG, "[MyReceiver] onReceive - " + intent.action + ", extras: " + printBundle(bundle!!))

            if (JPushInterface.ACTION_REGISTRATION_ID == intent.action) {
                val regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID)
                //Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId!!)
                //send the Registration Id to your server...

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED == intent.action) {
                //Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE)!!)
                processCustomMessage(context, bundle)

            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED == intent.action) {
                //Log.d(TAG, "[MyReceiver] 接收到推送下来的通知")
                messageNumber++
                ShortcutBadger.applyCount(context, messageNumber)
                val notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID)
                Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: $notifactionId")

            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED == intent.action) {
                Log.d(TAG, "[MyReceiver] 用户点击打开了通知")
                messageNumber=0
                ShortcutBadger.removeCount(context)
                //打开自定义的Activity
                var intent:Intent?=null
                if (AppUtils.isMainActivityAlive(context,"com.app.couponsharelife.ui.main.MainActivity")){
                    intent=Intent(context, MainActivity::class.java)
                }else{
                    intent=Intent(context, SplashActivity::class.java)
                }
                intent.putExtras(bundle)
                context.startActivity(intent)

            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK == intent.action) {
                //Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA)!!)
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

            } else if (JPushInterface.ACTION_CONNECTION_CHANGE == intent.action) {
                val connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false)
                //Log.w(TAG, "[MyReceiver]" + intent.action + " connected state change to " + connected)
            } else {
                //Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.action!!)
            }
        } catch (e: Exception) {

        }

    }

    // 打印所有的 intent extra 数据
    private fun printBundle(bundle: Bundle): String {
        val sb = StringBuilder()
        for (key in bundle.keySet()) {
            if (key == JPushInterface.EXTRA_NOTIFICATION_ID) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key))
            } else if (key == JPushInterface.EXTRA_CONNECTION_CHANGE) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key))
            } else if (key == JPushInterface.EXTRA_EXTRA) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Log.i(TAG, "This message has no Extra data")
                    continue
                }

                try {
                    val json = JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA))
                    val it = json.keys()

                    while (it.hasNext()) {
                        val myKey = it.next()
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]")
                    }
                } catch (e: JSONException) {
                    Log.e(TAG, "Get message extra JSON error!")
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.get(key))
            }
        }
        return sb.toString()
    }

    //send msg to MainActivity
    private fun processCustomMessage(context: Context, bundle: Bundle?) {
        if (bundle!=null){
            val channelID = "1"
            val channelName = "channel_name"
            var intent:Intent?=null
            if (AppUtils.isMainActivityAlive(context,"com.app.couponsharelife.ui.main.MainActivity")){
                intent=Intent(context, MainActivity::class.java)
                /*val extras = bundle.getString(JPushInterface.EXTRA_EXTRA)?:""
                if (extras.isNotEmpty()){
                    try {
                        val json=JSONObject(extras)
                        val type=json.opt("type") as String
                        val link=json.opt("link") as String
                        Log.e("eeee","app开着------>$type---->$link")
                        intent.putExtra("type",type)
                        intent.putExtra("link",link)
                    }catch (e: java.lang.Exception){

                    }
                }*/
            }else{
                intent=Intent(context, SplashActivity::class.java)
            }
            intent.putExtras(bundle)
            //intent!!.flags=Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
            val pendingIntent = PendingIntent.getActivity(context, 1000, intent, PendingIntent.FLAG_UPDATE_CURRENT)
            // 获得系统推送的自定义消息
            val message = bundle.getString(JPushInterface.EXTRA_MESSAGE)
            val notificationManager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            //适配安卓8.0的消息渠道
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH)
                notificationManager.createNotificationChannel(channel)
            }
            val notification = NotificationCompat.Builder(context, channelID)
            notification.setAutoCancel(true)
                    .setContentText(message)
                    .setContentTitle("券享生活")
                    .setSmallIcon(R.drawable.jpush_notification_icon)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setContentIntent(pendingIntent)
            notificationManager.notify((System.currentTimeMillis() / 1000).toInt(), notification.build())
        }
    }
}